//
//  AESCrypto.swift
//  Robot
//
//  Created by ming on 2025/2/18.
//

import Foundation
import CryptoKit
//import CryptoSwift

// MARK: -- AES加密，这里使用
public struct AESCrypto {
    public static func encrypt(plaintext: String, key: SymmetricKey, iv: Data) throws -> Data {
        guard let plaintextData = plaintext.data(using: .utf8) else {
            throw EncryptionError.encodingFailed
        }
        
        let nonce = try AES.GCM.Nonce(data: iv)
        let sealedBox = try AES.GCM.seal(plaintextData, using: key, nonce: nonce)
        
        return sealedBox.ciphertext + sealedBox.tag
    }
    
    public static func generateKey() -> SymmetricKey {
        return SymmetricKey(size: .bits256)
    }
    
    public static func generateIV() -> Data {
        return Data((0..<16).map { _ in UInt8.random(in: 0...255) })
    }
    
    enum EncryptionError: Error {
        case encodingFailed
    }
    
    public static func generateSymmetricKey(from string: String) throws -> SymmetricKey {
        guard let data = Data(base64Encoded: string) else {
            throw NSError(domain: "KeyGenerationError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 string"])
        }
        return SymmetricKey(data: data)
    }
}

// 使用 CryptoSwift
//struct AESCFBCrypto {
//    static let key = "BJtMMy/97VsmOHFRyqLJsW=="
//    static let ivSize = 16
//
//    // 加密
//    static func encrypt(_ string: String) throws -> String {
//        guard let keyData = Data(base64Encoded: key) else {
//            throw CryptoError.invalidKey
//        }
//
//        let iv = AES.randomIV(ivSize)
//        let aes = try AES(key: keyData.bytes, blockMode: CFB(iv: iv), padding: .noPadding)
//
//        guard let stringData = string.data(using: .utf8) else {
//            throw CryptoError.stringEncodingFailed
//        }
//
//        let encryptedBytes = try aes.encrypt(stringData.bytes)
//        let encryptedData = Data(iv + encryptedBytes)
//        return encryptedData.base64EncodedString()
//    }
//
//    // 解密
//    static func decrypt(_ string: String) throws -> String {
//        guard let keyData = Data(base64Encoded: key) else {
//            throw CryptoError.invalidKey
//        }
//
//        guard let data = Data(base64Encoded: string) else {
//            throw CryptoError.invalidInputString
//        }
//
//        let iv = data.prefix(ivSize)
//        let encryptedData = data.dropFirst(ivSize)
//
//        let aes = try AES(key: keyData.bytes, blockMode: CFB(iv: Array(iv)), padding: .noPadding)
//        let decryptedBytes = try aes.decrypt(encryptedData.bytes)
//
//        guard let decryptedString = String(bytes: decryptedBytes, encoding: .utf8) else {
//            throw CryptoError.decryptionFailed
//        }
//
//        return decryptedString
//    }
//
//    enum CryptoError: Error {
//        case invalidKey
//        case stringEncodingFailed
//        case invalidInputString
//        case decryptionFailed
//    }
//}
